/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SunSpotView.java
 *
 * Created on 22-may-2012, 12:55:00
 */
package org.sunspotUI;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.sunspotworld.AuroraMessage;
import org.sunspotworld.Service;
import org.sunspotworld.SunSpotHostApplication;

/**
 *
 * @author Migue
 */
public class SunSpotView extends javax.swing.JFrame {
    private SunSpotServicesView sssv;
    private SunSpotSnifferView ssfv;
    private GroupConnectionsView gcv;
    private Hashtable<String, List<Service>> services;
    private SunSpotHostApplication sha;
    
    /** Creates new form SunSpotView */
    public SunSpotView() {
        initComponents();
        sssv = new SunSpotServicesView();
        ssfv = new SunSpotSnifferView();
        ssfv.updateteAgentsSnifferList(agentsList.getItems());
        services = new Hashtable<String, List<Service>>();
        sha = null;
    }

    public SunSpotView(SunSpotHostApplication aThis) {
        initComponents();
        sha = aThis;
        sssv = new SunSpotServicesView(sha);
        ssfv = new SunSpotSnifferView();
        ssfv.updateteAgentsSnifferList(agentsList.getItems());
        //ssfv = new SunSpotSnifferView(sha);
        services = new Hashtable<String, List<Service>>();

        gcv = new GroupConnectionsView(sha);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PanelList = new javax.swing.JPanel();
        agentsList = new java.awt.List();
        PanelStatus = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        statusPane = new javax.swing.JTextPane();
        clearButton = new javax.swing.JButton();
        copyButton = new javax.swing.JButton();
        jToolBar1 = new javax.swing.JToolBar();
        removeAgentButton = new javax.swing.JButton();
        servicesButton = new javax.swing.JButton();
        snifferButton = new javax.swing.JButton();
        groupsButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Solution Agent Platform");

        PanelList.setBorder(javax.swing.BorderFactory.createTitledBorder("Agents List"));
        PanelList.setAutoscrolls(true);
        PanelList.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        agentsList.setBackground(new java.awt.Color(204, 255, 255));
        agentsList.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        agentsList.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        agentsList.setName(""); // NOI18N

        javax.swing.GroupLayout PanelListLayout = new javax.swing.GroupLayout(PanelList);
        PanelList.setLayout(PanelListLayout);
        PanelListLayout.setHorizontalGroup(
            PanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(agentsList, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
        );
        PanelListLayout.setVerticalGroup(
            PanelListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(agentsList, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
        );

        PanelStatus.setBorder(javax.swing.BorderFactory.createTitledBorder("Status Messages"));
        PanelStatus.setFocusable(false);

        statusPane.setEditable(false);
        statusPane.setForeground(new java.awt.Color(4, 157, 250));
        jScrollPane2.setViewportView(statusPane);

        clearButton.setText("Clear");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        copyButton.setText("Copy");
        copyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PanelStatusLayout = new javax.swing.GroupLayout(PanelStatus);
        PanelStatus.setLayout(PanelStatusLayout);
        PanelStatusLayout.setHorizontalGroup(
            PanelStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelStatusLayout.createSequentialGroup()
                .addComponent(clearButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(copyButton)
                .addGap(454, 454, 454))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
        );
        PanelStatusLayout.setVerticalGroup(
            PanelStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelStatusLayout.createSequentialGroup()
                .addGroup(PanelStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(clearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(copyButton, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
        );

        jToolBar1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 255, 255), 1, true));
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        File f = new File("");
        //String s = f.getAbsolutePath()+"\\src\\org\\images\\Unregister agent.png";
        String sep = System.getProperty("file.separator");
        String s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Unregister agent.png";
        removeAgentButton.setIcon(new javax.swing.ImageIcon(s));
        removeAgentButton.setToolTipText("Remove Agent");
        removeAgentButton.setFocusable(false);
        removeAgentButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removeAgentButton.setMaximumSize(new java.awt.Dimension(39, 39));
        removeAgentButton.setMinimumSize(new java.awt.Dimension(39, 39));
        removeAgentButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        removeAgentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeAgentButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(removeAgentButton);
        removeAgentButton.getAccessibleContext().setAccessibleDescription("");

        f = new File("");
        s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Services.png";
        servicesButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/images/Services.png"))); // NOI18N
        servicesButton.setToolTipText("Services");
        servicesButton.setFocusable(false);
        servicesButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        servicesButton.setMaximumSize(new java.awt.Dimension(39, 39));
        servicesButton.setMinimumSize(new java.awt.Dimension(39, 39));
        servicesButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        servicesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                servicesButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(servicesButton);

        f = new File("");
        s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Sniffer.png";
        snifferButton.setIcon(new javax.swing.ImageIcon(s));
        snifferButton.setToolTipText("Sniffer");
        snifferButton.setFocusable(false);
        snifferButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        snifferButton.setMaximumSize(new java.awt.Dimension(39, 39));
        snifferButton.setMinimumSize(new java.awt.Dimension(39, 39));
        snifferButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        snifferButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                snifferButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(snifferButton);

        f = new File("");
        s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Groups.png";
        groupsButton.setIcon(new javax.swing.ImageIcon(s));
        groupsButton.setToolTipText("Group connections");
        groupsButton.setFocusable(false);
        groupsButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        groupsButton.setMaximumSize(new java.awt.Dimension(39, 39));
        groupsButton.setMinimumSize(new java.awt.Dimension(39, 39));
        groupsButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        groupsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                groupsButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(groupsButton);
        groupsButton.getAccessibleContext().setAccessibleDescription("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
                    .addComponent(PanelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PanelList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PanelList, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(PanelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        PanelList.getAccessibleContext().setAccessibleName(null);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        // TODO add your handling code here:
        statusPane.setText("");
    }//GEN-LAST:event_clearButtonActionPerformed

    private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
        // TODO add your handling code here:
        StringSelection sers = new StringSelection(statusPane.getText());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sers, null);
    }//GEN-LAST:event_copyButtonActionPerformed

    private void servicesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_servicesButtonActionPerformed
        // TODO add your handling code here:
        sssv.setVisible(true);
    }//GEN-LAST:event_servicesButtonActionPerformed

    private void removeAgentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAgentButtonActionPerformed
        // TODO add your handling code here:
        if(agentsList.getItemCount()>0 && agentsList.getSelectedIndex()>=0){
            String id = agentsList.getSelectedItem();
            sha.unregisterConnectionAux(id);
            //this.removeAgentList(id);
        }
    }//GEN-LAST:event_removeAgentButtonActionPerformed

    private void snifferButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_snifferButton1ActionPerformed
        // TODO add your handling code here:
        //ssfv.updateteAgentsSnifferList(agentsList.getItems());
        ssfv.setVisible(true);
    }//GEN-LAST:event_snifferButton1ActionPerformed

    private void groupsButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupsButton1ActionPerformed
        // TODO add your handling code here:
        gcv.setVisible(true);
    }//GEN-LAST:event_groupsButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SunSpotView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SunSpotView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SunSpotView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SunSpotView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SunSpotView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelList;
    private javax.swing.JPanel PanelStatus;
    private java.awt.List agentsList;
    private javax.swing.JButton clearButton;
    private javax.swing.JButton copyButton;
    private javax.swing.JButton groupsButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton removeAgentButton;
    private javax.swing.JButton servicesButton;
    private javax.swing.JButton snifferButton;
    private javax.swing.JTextPane statusPane;
    // End of variables declaration//GEN-END:variables
    
    public void addAgentList(String id){
        String[] elements = agentsList.getItems();
        int num_elements = elements.length;
        int i=0;
        boolean found = false;
        while(i<num_elements && !found){
            found = elements[i].equals(id);
            i++;
        }
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();        
        if(!found){
            agentsList.add(id);
            String message = "["+date+"] The agent \""+id+"\" was correctly registered\n";
            this.appendTextStatus(message,Color.blue);
            ssfv.addAgent(id);
        }
        else{
            String message = "["+date+"] Error found: The agent \""+id+"\" is already registered\n";
            this.appendTextStatus(message,Color.red);
        }
        ssfv.updateteAgentsSnifferList(agentsList.getItems());
    }
    
    public void removeAgentList(String id){
        String[] elements = agentsList.getItems();
        int i=0;
        boolean found = false;
        while(!found && i<elements.length){
            found = elements[i].equals(id);
            i++;
        }
        //DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        String message;
        if(found){
            agentsList.remove(id);
            message = "["+date+"] The agent \""+id+"\" was correctly unregistered\n";
            this.appendTextStatus(message,Color.blue);
            ssfv.removeAgent(id);
        }else{
            message = "["+date+"] Error found: The agent \""+id+"\" could not unregister\n";
            this.appendTextStatus(message,Color.red);
        }
        ssfv.updateteAgentsSnifferList(agentsList.getItems());

    }
    
    public void addStatusMessage(String message){
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date(); 
        appendTextStatus("["+date+"] "+message+"\n", Color.black);
    }

    private void appendTextStatus(String message, Color c) {
        if (c==null) c=Color.black;
        StyledDocument doc = statusPane.getStyledDocument();

        Style style = statusPane.addStyle(null, null);
        StyleConstants.setForeground(style, c);

        try { doc.insertString(doc.getLength(),message,style);}
        catch (BadLocationException e){}
    }

    public void setServices(Hashtable<String, List<Service>> services) {
        this.services = services;
        sssv.addServicesTable(services);
    }

    public void notifyServicesRemoved() {
        Date date = new Date();
        String message = "Service(s) did remove correctly";
        appendTextStatus("["+date+"] "+message+"\n", Color.blue);
        sssv.statusServices(message, Color.blue);
    }
    
    
    public void notifyServicesRemoved(String type, String nameService, String owner) {
        Date date = new Date();
        String message;
        if (type.equals("") && nameService.equals("")) {
            message = "All services from \""+owner+"\" of every type were removed correctly";
        }else{
            message = "Service \""+nameService+"\" of type \""+type+"\" and owner \""+owner+"\" were removed correctly";
        }
        appendTextStatus("["+date+"] "+message+"\n", Color.blue);
        sssv.statusServices(message, Color.blue);
    }
    
    public void notifyServiceAdded(String type, Service ser){
        Date date = new Date();
        String message = "Service \""+ser.getName()+"\", which type is \""+type+"\" and owner is \""+ser.getOwner()+"\", were added correctly";
        appendTextStatus("["+date+"] "+message+"\n", Color.blue);
        sssv.statusServices(message, Color.blue);
    }
    
    public void notifyGroupAdded(String groupName) {
        Date date = new Date();
        String message = "Group connection \""+groupName+"\" registered correctly";
        appendTextStatus("["+date+"] "+message+"\n", Color.blue);
    }
    
    public void notifyGroupRemoved(String groupName) {
        Date date = new Date();
        String message = "Group connection \""+groupName+"\" unregistered correctly";
        appendTextStatus("["+date+"] "+message+"\n", Color.blue);
    }
    
    public void notifyAgentGroupRemoved(String groupName, String agent, boolean registered) {
        Date date = new Date();
        String message;
        if(registered){
            message = "Agent \""+agent+"\" from group connection \""+groupName+"\" unregistered correctly";
            appendTextStatus("["+date+"] "+message+"\n", Color.blue);
        }else{
            //message = "Agent \""+agent+"\" doesn't exist in group connection \""+groupName+"\"";
            //appendTextStatus("["+date+"] "+message+"\n", Color.red);
        }
    }

    private String resolvePath(String absolutePath) {
        return absolutePath;
    }

    public void addConnectionToSniffer(String sender, Vector<String> receivers, String converstionId, String content) {
        String s;
        //if(receivers!=null && !receivers.isEmpty()){
            ssfv.checkAgents(sender);
        //}
        for (Iterator<String> it = receivers.iterator(); it.hasNext();) {
            s = it.next();
            ssfv.checkAgents(s);
            ssfv.addConnection(sender, s, "["+converstionId+"] "+content);
        }
    }

    public void updateGroups() {
        gcv.updateGroups();
        ssfv.updateGroups(sha.getIdGroups());
    }
    
    public void updateGroups(List<String> groups) {
        gcv.updateGroups(groups);
    }

    public void updateGroups(String id_group) {
        gcv.updateGroups();
        ssfv.addAgent(id_group);
        ssfv.updateGroups(sha.getIdGroups());
    }
    
    public void updateAgents() {
        gcv.updateAgents();
    }
    
    public void removeGroupSniffer(String id){
        ssfv.removeAgent(id);
    }
}
